package com.yangrd.airship.generator.config;

import org.apache.logging.log4j.util.Strings;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;

import java.lang.annotation.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author yangrd
 * @date 2021/11/13
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional({OnExistPropertyCondition.class})
public @interface ConditionalOnExistProperty {

    String prefix() default "";

    String[] value() default {};
}

class OnExistPropertyCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> attrs = metadata.getAnnotationAttributes(ConditionalOnExistProperty.class.getName());
        String[] values = (String[]) attrs.get("value");
        String prefix = (String) attrs.get("prefix");
        for (String value : values) {
            String key = prefix + "." + value;
            String property = context.getEnvironment().getProperty(key);
            if (Strings.isNotBlank(property)) {
                return true;
            }
        }
        return false;
    }
}
